package com.weiquan.controller;

import com.weiquan.annotation.ApiLog;
import com.weiquan.common.Result;
import com.weiquan.dto.LoginRequest;
import com.weiquan.dto.RegisterRequest;
import com.weiquan.service.SysUserService;
import com.weiquan.utils.IpUtils;
import com.weiquan.vo.LoginResponse;
import com.weiquan.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;

/**
 * 用户认证控制器
 * 
 * @author weiquan
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@Validated
public class AuthController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 用户注册
     */
    @ApiLog(value = "用户注册", operationType = "用户管理")
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterRequest request) {
        sysUserService.register(request);
        return Result.success();
    }

    /**
     * 用户登录
     */
    @ApiLog(value = "用户登录", operationType = "用户管理")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        LoginResponse response = sysUserService.login(request);
        
        // 更新登录信息
        String loginIp = IpUtils.getClientIp(httpRequest);
        sysUserService.updateLoginInfo(response.getUserInfo().getId(), loginIp);
        
        return Result.success(response);
    }

    /**
     * 发送短信验证码
     */
    @ApiLog(value = "发送短信验证码", operationType = "用户管理")
    @PostMapping("/send-sms")
    public Result sendSmsCode(@RequestParam @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phone) {
        sysUserService.sendSmsCode(phone);
        return Result.success("验证码发送成功");
    }

    /**
     * 获取用户信息
     */
    @ApiLog(value = "获取用户信息", operationType = "用户管理")
    @GetMapping("/user-info")
    public Result<UserInfoVO> getUserInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        UserInfoVO userInfo = sysUserService.getUserInfo(userId);
        return Result.success(userInfo);
    }

    /**
     * 更新用户信息
     */
    @ApiLog(value = "更新用户信息", operationType = "用户管理")
    @PutMapping("/user-info")
    public Result updateUserInfo(@Valid @RequestBody UserInfoVO userInfo, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        sysUserService.updateUserInfo(userId, userInfo);
        return Result.success("用户信息更新成功");
    }
}